/**
 * Copyright (c) 2022 Presto Labs Pte. Ltd.
 * Author: Ju
 */

#include "coin2/exchange/base/order/control/network/tcp_connection.h"

#include <glog/logging.h>

namespace coin2::exchange::base::order {

TcpConnection::TcpConnection(boost::asio::io_context *ioc)
    : ioc_(ioc), strand_(*ioc), socket_(*ioc), buffer_(MAX_SIZE) {}

TcpConnection::~TcpConnection() { Close(); }

void TcpConnection::Close() {
  socket_.close();
  LOG(INFO) << "Tcp DisConnection";
}

void TcpConnection::Start() {
  auto self = shared_from_this();
  boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield) {
    while (true) {
      boost::system::error_code ec;
      std::size_t n = socket_.async_read_some(
          boost::asio::buffer(buffer_.data(), MAX_SIZE), yield[ec]);
      if (ec) {
        break;
      }
      callback_->OnRawDataReceived(self, buffer_.data(), n);
    }
  });
}

void TcpConnection::SendMsg(std::string buffer) {
  socket_.async_write_some(boost::asio::buffer(buffer.data(), buffer.size()),
                           [this](boost::system::error_code ec, std::size_t n) {
                             if (ec) {
                               LOG(ERROR) << " tcp connection sendmsg error.";
                             }
                           });
}

}  // namespace coin2::exchange::base::order